<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>3001</h1>
    <button type="button" id="login">login</button>

    <button type="button" id="profile">profile</button>

    <script src="https://andremao.gitee.io/cdn/cross-local-storage.js"></script>

    <script>
      (() => {
        // 设置要从哪些域获取 localStorage，多个用逗号隔开
        // 这些域均需要有一个 /cross-local-storage.html 路由，响应一个 html 页面
        // 并在页面中引入 https://andremao.gitee.io/cdn/cross-local-storage.js 脚本，然后调用 crossLocalStorage.setConsumerOrigins(...); 做支持
        crossLocalStorage.setProviderOrigins('http://localhost:3002');

        if (!localStorage.getItem('token')) {
          crossLocalStorage
            // 获取某域下的某个 localStorage Item，注意：域名必须在 setProviderOrigins 参数列表中
            .getItem('http://localhost:3002', 'token')
            .then((value) => {
              console.log(value, 'hehe');
              if (value) {
                localStorage.setItem('token', value);
              }
            });
        }

        document.querySelector('#login').addEventListener('click', () => {
          fetch('/login', {
            method: 'post',
            body: JSON.stringify({
              uname: 'andremao',
              upwd: 'qwe123',
            }),
            headers: {
              'Content-Type': 'application/json',
            },
          })
            .then((res) => res.json())
            .then((data) => {
              console.log(data);
              localStorage.setItem('token', data.token);
            });
        });

        document.querySelector('#profile').addEventListener('click', () => {
          fetch('/profile', {
            headers: {
              Authorization: 'Bearer ' + localStorage.getItem('token'),
            },
          })
            .then((res) => res.json())
            .then((data) => {
              console.log(data);
            });
        });
      })();
    </script>
  </body>
</html>
